//曾凡诚
#include "ParamConfigDlg.h"
#include "ui_ParamConfigDlg.h"
#include <QMessageBox>

ParamConfigDlg::ParamConfigDlg(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ParamConfigDlg)
{
    ui->setupUi(this);
    setWindowTitle("Simulator参数配置");
}

ParamConfigDlg::~ParamConfigDlg()
{
    delete ui;
}

// 【关键】回显Simulator当前参数到输入框
void ParamConfigDlg::setInitParams(float dieselMax, float dieselMin, float dieselCost, float essCap)
{
    ui->editDieselMax->setText(QString::number(dieselMax, 'f', 1));  // 保留1位小数
    ui->editDieselMin->setText(QString::number(dieselMin, 'f', 1));
    ui->editDieselCost->setText(QString::number(dieselCost, 'f', 2)); // 成本保留2位小数
    ui->editEssCap->setText(QString::number(essCap, 'f', 1));
}

// 保存按钮：校验输入+传新值
void ParamConfigDlg::on_btnSave_clicked()
{
    // 1. 读取输入并转成float（校验是否为合法数字）
    bool ok1, ok2, ok3, ok4;
    float dieselMax = ui->editDieselMax->text().toFloat(&ok1);
    float dieselMin = ui->editDieselMin->text().toFloat(&ok2);
    float dieselCost = ui->editDieselCost->text().toFloat(&ok3);
    float essCap = ui->editEssCap->text().toFloat(&ok4);

    // 2. 校验参数合法性（避免负数、最小>最大）
    if (!ok1 || !ok2 || !ok3 || !ok4) {
        QMessageBox::warning(this, "错误", "请输入数字！");
        return;
    }
    if (dieselMax <= 0 || dieselMin < 0 || dieselCost <= 0 || essCap <= 0) {
        QMessageBox::warning(this, "错误", "参数不能为负！");
        return;
    }
    if (dieselMin > dieselMax) {
        QMessageBox::warning(this, "错误", "最小出力不能大于最大出力！");
        return;
    }

    // 3. 发射信号，把新参数传给MainWindow
    emit paramsSaved(dieselMax, dieselMin, dieselCost, essCap);
    accept(); // 关闭弹窗
}

// 取消按钮：直接关弹窗
void ParamConfigDlg::on_btnCancel_clicked()
{
    reject();
}
